`<template>
    <div class="editor-container">
        <!-- 文档标题栏 -->
        <div class="document-header">
            <div class="left-section">
                <el-input v-model="title" placeholder="请输入标题" class="title-input" :prefix-icon="Edit" />
            </div>
            <div class="right-section">
                <el-button type="primary" @click="saveDocument" :loading="isSaving">
                    保存文档
                </el-button>
            </div>
        </div>

        <!-- CKEditor工具栏容器 -->
        <div class="document-toolbar"></div>

        <!-- 编辑器主体 -->
        <div class="editor-main" ref="editorElement"></div>

        <!-- 状态栏 -->
        <div class="editor-statusbar">
            <span>字数：{{ wordCount }}</span>
            <span>字符数：{{ charCount }}</span>
        </div>
    </div>
</template>

<script setup>
import { ref, shallowRef, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Edit } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
import DecoupledEditor from '@ckeditor/ckeditor5-build-decoupled-document'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
const baseURL = 'http://127.0.0.1:3000'
// 状态变量
const title = ref('')
const editorElement = ref(null)
const editor = shallowRef(null)
const isSaving = ref(false)
const wordCount = ref(0)
const charCount = ref(0)

// 获取随记数据
const fetchNoteData = async () => {
    if (route.params.id) {
        try {
            const response = await fetch(`${baseURL}/api/notes/${route.params.id}`, {
                credentials: 'include',
                headers: {
                    'Authorization': 'Bearer ' + userStore.token
                }
            })
            if (!response.ok) throw new Error('获取随记失败')
            const note = await response.json()
            title.value = note.title
            if (editor.value) {
                editor.value.setData(note.content || '')
            }
        } catch (error) {
            ElMessage.error(error.message)
        }
    }
}

// 更新字数统计
const updateWordCount = () => {
    if (!editor.value) return

    const content = editor.value.getData()
    // 移除HTML标签
    const plainText = content.replace(/<[^>]*>/g, '')

    // 计算字符数
    charCount.value = plainText.length

    // 计算单词数（中文按字计算，英文按空格分隔计算）
    const words = plainText.trim().split(/\s+/)
    const chineseChars = plainText.match(/[\u4e00-\u9fa5]/g) || []

    // 英文单词数加中文字数
    wordCount.value = words.length + chineseChars.length - words.join('').match(/[\u4e00-\u9fa5]/g)?.length || 0
}

// 初始化编辑器
onMounted(async () => {
    try {
        // 创建编辑器
        editor.value = await DecoupledEditor.create(editorElement.value, {
            language: 'zh-cn',
            placeholder: '开始输入内容...',
            toolbar: {
                items: [
                    'heading',
                    '|',
                    'bold',
                    'italic',
                    'underline',
                    'strikethrough',
                    'link',
                    '|',
                    'bulletedList',
                    'numberedList',
                    '|',
                    'fontColor',
                    'fontBackgroundColor',
                    '|',
                    'alignment',
                    'indent',
                    'outdent',
                    '|',
                    'imageUpload',
                    'blockQuote',
                    'insertTable',
                    'mediaEmbed',
                    '|',
                    'undo',
                    'redo'
                ]
            },
            image: {
                toolbar: [
                    'imageStyle:inline',
                    'imageStyle:block',
                    'imageStyle:side',
                    '|',
                    'toggleImageCaption',
                    'imageTextAlternative',
                    '|',
                    'linkImage'
                ]
            },
            table: {
                contentToolbar: [
                    'tableColumn',
                    'tableRow',
                    'mergeTableCells',
                    'tableCellProperties',
                    'tableProperties'
                ]
            }
        })

        // 将工具栏添加到容器中
        const toolbarContainer = document.querySelector('.document-toolbar')
        toolbarContainer.appendChild(editor.value.ui.view.toolbar.element)

        // 监听内容变化
        editor.value.model.document.on('change:data', () => {
            updateWordCount()
        })

        // 设置快捷键
        setupKeyboardShortcuts()
        
        // 加载笔记数据
        await fetchNoteData()
    } catch (error) {
        console.error('编辑器初始化失败:', error)
        ElMessage.error('编辑器加载失败，请刷新页面重试')
    }
})

// 清理
onBeforeUnmount(() => {
    if (editor.value) {
        editor.value.destroy()
    }
})

// 保存文件
const saveDocument = async () => {
    if (!editor.value) return

    try {
        isSaving.value = true
        const content = editor.value.getData()

        let url, method
        const data = {
            title: title.value,
            content: content
        }

        if (route.params.id) {
            // 更新已有文档
            url = `${baseURL}/api/notes/${route.params.id}`
            method = 'PUT'
        } else {
            // 创建新文档
            url = `${baseURL}/api/notes/documents`
            method = 'POST'
            if (route.query.repositoryId) {
                data.repositoryId = parseInt(route.query.repositoryId)
            }
        }

        const response = await fetch(url, {
            method: method,
            credentials: 'include',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + userStore.token
            },
            body: JSON.stringify(data)
        })

        if (!response.ok) {
            throw new Error('保存失败')
        }

        const savedNote = await response.json()
        ElMessage.success('保存成功')

        // 如果是新建随记，保存后跳转到编辑模式
        if (!route.params.id) {
            router.replace(`/file/${savedNote.id}`)
        }
    } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败，请重试')
    } finally {
        isSaving.value = false
    }
}

// 添加快捷键支持
const setupKeyboardShortcuts = () => {
    document.addEventListener('keydown', (event) => {
        // Ctrl+S 保存文档
        if ((event.ctrlKey || event.metaKey) && event.key === 's') {
            event.preventDefault()
            saveDocument()
        }
    })
}
</script>

<style scoped>
.editor-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 20px;
}

.document-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.left-section {
    flex: 1;
    margin-right: 20px;
}

.title-input {
    width: 100%;

    :deep(.el-input__wrapper) {
        font-size: 18px;
        padding: 8px 12px;
    }
}

.right-section {
    display: flex;
    align-items: center;
    gap: 12px;
}



.document-toolbar {
    margin-bottom: 20px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background: #f5f7fa;
    padding: 8px;
}

.editor-main {
    flex: 1;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 20px;
    overflow-y: auto;
    min-height: 400px;
    background: #fff;
}

.editor-statusbar {
    display: flex;
    justify-content: flex-end;
    gap: 16px;
    padding: 8px 12px;
    color: #909399;
    font-size: 14px;
    border-top: 1px solid #dcdfe6;
    margin-top: 10px;
}

/* CKEditor 相关样式 */
:deep(.ck-editor__editable) {
    min-height: 500px;
    font-size: 16px;
    line-height: 1.6;
    padding: 20px;
}

:deep(.ck-toolbar) {
    border: none !important;
    background: transparent !important;
}

:deep(.ck-content) {
    & h1 {
        font-size: 28px;
        margin-top: 24px;
        margin-bottom: 16px;
        color: #303133;
    }

    & h2 {
        font-size: 24px;
        margin-top: 20px;
        margin-bottom: 14px;
        color: #303133;
    }

    & h3 {
        font-size: 20px;
        margin-top: 18px;
        margin-bottom: 12px;
        color: #303133;
    }

    & p {
        margin-bottom: 12px;
    }

    & ul,
    & ol {
        padding-left: 24px;
        margin-bottom: 12px;
    }

    & blockquote {
        border-left: 4px solid #409EFF;
        padding: 12px 20px;
        margin: 16px 0;
        background: #ecf5ff;
        font-style: italic;
    }

    & img {
        max-width: 100%;
        height: auto;
        margin: 12px 0;
        border-radius: 4px;
    }

    & table {
        border-collapse: collapse;
        width: 100%;
        margin: 16px 0;

        th,
        td {
            border: 1px solid #dcdfe6;
            padding: 8px 12px;
        }

        th {
            background: #f5f7fa;
            font-weight: bold;
        }
    }

    & code {
        background: #f5f7fa;
        padding: 2px 4px;
        border-radius: 3px;
        font-family: monospace;
    }

    & pre {
        background: #303133;
        color: #ffffff;
        padding: 16px;
        border-radius: 4px;
        overflow-x: auto;
        font-family: monospace;
    }

    & .todo-list {
        list-style-type: none;
        padding-left: 10px;
    }

    & .todo-list__label {
        display: flex;
        align-items: center;
    }

    & .todo-list .todo-list__checkbox {
        margin-right: 8px;
    }
}
</style>`
